/**
 * Created with JetBrains WebStorm.
 * User: a_polyakov
 * Date: 07.03.13
 * Time: 0:03
 * To change this template use File | Settings | File Templates.
 */
var models = require('./DataClasses');
var utils = require('../utils/utils');
var fs = require("fs");

exports.initTestData = function (model) {
    for (var i = 1; i <= 50; i++) {
        var countryFileName = 'country' + ((i < 10) ? '0' : '') + i;
        var country = model.addCountry(utils.getFileName(countryFileName), countryFileName);
        for (var j = 1; j <= i; j++) {
            var cityFileName = 'city' + ((j < 10) ? '0' : '') + j;
            var city = country.addCity(utils.getFileName(cityFileName), cityFileName);
            for (var k = 1; k <= j; k++) {
                var department = new models.Department(utils.getFileName("name" + k), "name" + k, "address" + k, "ZipCode" + k, "Flag1" + k, "phone" + k);
                city.addDepartment(department);
                for (var l = 1; l <= k; l++) {
                    var departmentWorkTime = new models.DepartmentWorkTime("day", "time");
                    department.work_time_list.push(departmentWorkTime);
                }
                for (var l = 1; l <= k; l++) {
                    var departmentService = new models.DepartmentService("service" + l);
                    department.service_list.push(departmentService);
                }
            }
        }
    }
}

exports.initWord2 = function (model) {
//    var file_handle = fs.openSync("data/word2.txt", "r", 0644);
    readLines('data/' + model.data_file_name, function (line) {
        // Armenia <-> Bolnisi <-> Privatbank <-> Sulkhan-saba St. 101 <-> 1100 <-> False <-> Monday:10:00 AM - 5:30 PM,Tuesday:10:00 AM - 5:30 PM,Wednesday:10:00 AM - 5:30 PM,Thursday:10:00 AM - 5:30 PM,Friday:10:00 AM - 5:30 PM,Saturday:10:00 AM - 1:30 PM,Sunday:Closed <-> money transfer,quick cash,quick pay
        var allowedFormats = false;
        var indexA = line.indexOf(' <-> ');
        if (indexA > 0) {
            var countryName = line.substring(0, indexA);
            var countryFileName = utils.getFileName(countryName);
            var indexB = line.indexOf(' <-> ', indexA + 5);
            if (indexB > 0) {
                var cityName = line.substring(indexA + 5, indexB);
                var cityFileName = utils.getFileName(cityName);
                indexA = line.indexOf(' <-> ', indexB + 5);
                if (indexA > 0) {
                    var departmentName = line.substring(indexB + 5, indexA);
                    var departmentFileName = utils.getFileName(departmentName);
                    indexB = line.indexOf(' <-> ', indexA + 5);
                    if (indexB > 0) {
                        var departmentAddress = line.substring(indexA + 5, indexB);
                        indexA = line.indexOf(' <-> ', indexB + 5);
                        if (indexA > 0) {
                            var departmentZipCode = line.substring(indexB + 5, indexA);
                            indexB = line.indexOf(' <-> ', indexA + 5);
                            if (indexB > 0) {
                                var departmentFlag1 = line.substring(indexA + 5, indexB);
                                indexA = line.indexOf(' <-> ', indexB + 5);
                                if (indexA > 0) {
                                    allowedFormats = true;
                                    var departmentWorkingTime = line.substring(indexB + 5, indexA);
                                    var departmentServices = line.substring(indexA + 5);

                                    var country = model.addCountry(countryFileName, countryName);

                                    var city = country.addCity(cityFileName, cityName);

                                    var department = new models.Department(departmentFileName, departmentName, departmentAddress, departmentZipCode, departmentFlag1, "");
                                    city.addDepartment(department);

                                    if (departmentWorkingTime != null && departmentWorkingTime.length > 0) {
                                        var workTimeArray = departmentWorkingTime.split(",");
                                        for (var i = 0; i < workTimeArray.length; i++) {
                                            var workTime = workTimeArray[i];
                                            var index = workTime.indexOf(':');
                                            if (index > 0 && index < workTime.length) {
                                                var departmentWorkTime = new models.DepartmentWorkTime(workTime.substring(0, index), workTime.substring(index + 1));
                                                department.work_time_list.push(departmentWorkTime);
                                            } else {
                                                console.log('Error format column work time to line ' + line);
                                            }
                                        }
                                    }

                                    if (departmentServices != null && departmentServices.length > 0) {
                                        var serviceArray = departmentServices.split(",");
                                        for (var i = 0; i < serviceArray.length; i++) {
                                            var service = serviceArray[i];
                                            var departmentService = new models.DepartmentService(service);
                                            department.service_list.push(departmentService);
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
        }
        if (!allowedFormats) {
            console.log('Error format line ' + line);
        }
    });
}

exports.initMoneygram = function (model) {
    readLines('data/' + model.data_file_name, function (line) {

        //MoneyGram - BANGLADESH - BRAMHAN BARIA - ISLAMI BANK AKHAURA SME BRANCH - #216 -  AKHAURA CHANDURA ROAD &nbsp;1ST FLOOR AKHAURA SME SERVICE CENTER NOORJAHAN MANJEEL BRAMHAN BARIA, 3400 01730326104   Mon-Thu 10:00-16:00 Fri-Sat 00:00-00:00 Sun 10:00-16:00
        var allowedFormats = false;
        var indexA = line.indexOf(" - ");
        if (indexA > 0) {
            var indexB = line.indexOf(" - ", indexA + 3);
            if (indexB > 0) {
                var countryName = line.substring(indexA + 3, indexB);
                var countryFileName = utils.getFileName(countryName);
                indexA = line.indexOf(" - ", indexB + 3);
                if (indexA > 0) {
                    var cityName = line.substring(indexB + 3, indexA);
                    var cityFileName = utils.getFileName(cityName);
                    indexB = line.indexOf(" -  ", indexA + 3);
                    if (indexB > 0) {
                        var departmentName = line.substring(indexA + 3, indexB);
                        var departmentFileName = utils.getFileName(departmentName);
                        var indexWorkTime = line.indexOf("   ", indexB + 4);
                        if (indexWorkTime > 0) {
                            var indexPhone = line.lastIndexOf(" ", indexWorkTime - 1);
                            if (indexPhone > 0) {
                                var indexZipCode = line.lastIndexOf(", ", indexPhone - 1);
                                if (indexZipCode > 0) {
                                    var departmentAddress = line.substring(indexB + 4, indexZipCode);
                                    var departmentZipCode = "";
                                    if (indexPhone - indexZipCode > 5) {
                                        departmentZipCode = line.substring(indexZipCode + 2, indexPhone);
                                    }
                                    allowedFormats = true;
                                    var departmentPhone = line.substring(indexPhone, indexWorkTime);

                                    var country = model.addCountry(countryFileName, countryName);

                                    var city = country.addCity(cityFileName, cityName);

                                    var department = new models.Department(departmentFileName, departmentName, departmentAddress, departmentZipCode, '', departmentPhone);
                                    city.addDepartment(department);

                                    var i = indexWorkTime + 3;
                                    while (i > 0 && i < line.length) {
                                        indexA = line.indexOf(' ', i);
                                        if (indexA > 0) {
                                            indexB = line.indexOf(' ', indexA + 1);
                                            if (indexB < 0) {
                                                indexB = line.length;
                                            }
                                            var departmentWorkTime = new models.DepartmentWorkTime(line.substring(i, indexA), line.substring(indexA + 1, indexB));
                                            department.work_time_list.push(departmentWorkTime);
                                            i = indexB + 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!allowedFormats) {
            console.log('Error format line ' + line);
        }
    });
}

exports.initRandomText = function (model) {

    readLines('data/' + model.text_file_name, function (line) {
        model.text_list.push(line);
    });

    if (fs.existsSync(model.base_dir+'data/text_link.txt')) {
//        чтение
        readLines(model.base_dir+'data/text_link.txt', function (line) {
            var indexA = line.indexOf(' <-> ');
            if (indexA > 0) {
                var map_key = line.substring(0, indexA);
                var map_value = line.substring(indexA + 5).split(', ');
                var array = [];
                for (var i = 0; i < map_value.length; i++) {
                    if (map_value[i] != '' && map_value[i] < model.text_list.length) {
                        array.push(model.text_list[map_value[i]]);
                    }
                }
                model.text_map[map_key] = array;
            }
        })
    }
    else {
//        генерация и запись в файл
        var fd = fs.openSync(model.base_dir+'data/text_link.txt', "w", 0644);

        randomText(model.text_map, '/about.html', model.text_list, model.minRandomText, model.maxRandomText, fd);

        var pageCount = (model.indexPageSize > 0) ? Math.ceil(model.country_list.length / model.indexPageSize) : 1;
        for (var l = 1; l <= pageCount; l++) {
            randomText(model.text_map, '/' + l, model.text_list, model.minRandomText, model.maxRandomText, fd);
        }
        for (var k = 0; k < model.country_list.length; k++) {
            var country = model.country_list[k];
            pageCount = (model.countryPageSize > 0) ? Math.ceil(country.city_list.length / model.countryPageSize) : 1;
            for (var l = 1; l <= pageCount; l++) {
                randomText(model.text_map, '/' + country.file_name + '/' + l, model.text_list, model.minRandomText, model.maxRandomText, fd);
            }
        }
        for (var j = 0; j < model.country_list.length; j++) {
            var country = model.country_list[j];
            for (var k = 0; k < country.city_list.length; k++) {
                var city = country.city_list[k];
                pageCount = (model.cityPageSize > 0) ? Math.ceil(city.department_list.length / model.cityPageSize) : 1;
                for (var l = 1; l <= pageCount; l++) {
                    randomText(model.text_map, '/' + country.file_name + '/' + city.file_name + '/' + l, model.text_list, model.minRandomText, model.maxRandomText, fd);
                }
            }
        }
        for (var i = 0; i < model.country_list.length; i++) {
            var country = model.country_list[i];
            for (var j = 0; j < country.city_list.length; j++) {
                var city = country.city_list[j];
                for (var k = 0; k < city.department_list.length; k++) {
                    var department = city.department_list[k];
                    randomText(model.text_map, '/' + country.file_name + '/' + city.file_name + '/' + department.file_name, model.text_list, model.minRandomText, model.maxRandomText, fd);
                }
            }
        }
        fs.close(fd);
    }
}


exports.initRandomLink = function (model) {

    if (fs.existsSync(model.base_dir+'data/anchor_link.txt')) {
//        чтение
        readLines(model.base_dir+'data/anchor_link.txt', function (line) {
            var indexA = line.indexOf(' <-> ');
            if (indexA > 0) {
                var map_key = line.substring(0, indexA);
                var map_value = line.substring(indexA + 5).split(', ');
                var array = [];
                for (var i = 0; i < map_value.length; i++) {
                    if (map_value[i] != '') {
                        var s = map_value[i];
                        var indexA = s.indexOf('/');
                        var country_file_name;
                        var city_file_name;
                        var department_file_name;
                        if (indexA == 0) {
                            indexA = s.indexOf('/', indexA + 1);
                            if (indexA > 0) {
                                country_file_name = s.substring(1, indexA);
                                var indexB = s.indexOf('/', indexA + 1);
                                if (indexB > 0) {
                                    city_file_name = s.substring(indexA + 1, indexB);
                                    department_file_name = s.substring(indexB + 1);
                                }
                                else {
                                    city_file_name = s.substring(indexA + 1);
                                }
                            } else {
                                country_file_name = s.substring(1);
                            }
                        }

                        var o = {};
                        var country = model.getCountry(country_file_name);
                        o.country = country;
                        var city = country.getCity(city_file_name);
                        if (city != null) {
                            o.city = city;
                            var department = city.getDepartment(department_file_name);
                            if (department != null) {
                                o.department = department;
                            }
                        }
                        array.push(o);
                    }
                }
                model.link_map[map_key] = array;
            }
        })
    }
    else {
//        генерация и запись в файл
        var fd = fs.openSync(model.base_dir+'data/anchor_link.txt', "w", 0644);

        randomLink(model.link_map, '/about.html', model, model.minRandomLink, model.maxRandomLink, fd);

        var pageCount = (model.indexPageSize > 0) ? Math.ceil(model.country_list.length / model.indexPageSize) : 1;
        for (var l = 1; l <= pageCount; l++) {
            randomLink(model.link_map, '/' + l, model, model.minRandomLink, model.maxRandomLink, fd);
        }
        for (var k = 0; k < model.country_list.length; k++) {
            var country = model.country_list[k];
            pageCount = (model.countryPageSize > 0) ? Math.ceil(country.city_list.length / model.countryPageSize) : 1;
            for (var l = 1; l <= pageCount; l++) {
                randomLink(model.link_map, '/' + country.file_name + '/' + l, model, model.minRandomLink, model.maxRandomLink, fd);
            }
        }
        for (var j = 0; j < model.country_list.length; j++) {
            var country = model.country_list[j];
            for (var k = 0; k < country.city_list.length; k++) {
                var city = country.city_list[k];
                pageCount = (model.cityPageSize > 0) ? Math.ceil(city.department_list.length / model.cityPageSize) : 1;
                for (var l = 1; l <= pageCount; l++) {
                    randomLink(model.link_map, '/' + country.file_name + '/' + city.file_name + '/' + l, model, model.minRandomLink, model.maxRandomLink, fd);
                }
            }
        }
        for (var i = 0; i < model.country_list.length; i++) {
            var country = model.country_list[i];
            for (var j = 0; j < country.city_list.length; j++) {
                var city = country.city_list[j];
                for (var k = 0; k < city.department_list.length; k++) {
                    var department = city.department_list[k];
                    randomLink(model.link_map, '/' + country.file_name + '/' + city.file_name + '/' + department.file_name, model, model.minRandomLink, model.maxRandomLink, fd);
                }
            }
        }
        fs.close(fd);
    }
}

function readLines(file_name, func) {
    var file_handle = fs.openSync(file_name, "r", 0644);
    var remaining = '';
    var data = fs.readSync(file_handle, 10000, null, 'ascii');
    while (data[1] > 0) {
        remaining += data[0];
        var index;
        while ((index = remaining.indexOf('\n')) > -1) {
            var line = remaining.substring(0, index);
            remaining = remaining.substring(index + 1);
            func(line);
        }
        data = fs.readSync(file_handle, 10000, null, 'ascii');
    }
    func(remaining);
    fs.close(file_handle);
}

function randomText(text_map, map_key, text_list, minRandomText, maxRandomText, fd) {
    var array = [];
    var arrayIndex = [];
    var count = nextRandomInt(minRandomText, maxRandomText);
    for (var i = 0; i < count; i++) {
        var index = nextRandomInt(0, text_list.length - 1)
        arrayIndex.push(index);
        array.push(text_list[index]);
    }
    text_map[map_key] = array;
    fs.writeSync(fd, map_key + ' <-> ' + arrayIndex.join(', ') + '\n');
}

function randomLink(link_map, map_key, model, minRandomLink, maxRandomLink, fd) {
    var array = [];
    var arrayFileName = [];
    var count = nextRandomInt(minRandomLink, maxRandomLink);
    for (var i = 0; i < count; i++) {
        var type = nextRandomInt(0, 2);
        var country = null;
        var city = null;
        var department = null;
        var o = {};
        var file_name = '';
        if (type == 0 || type == 1 || type == 2) {
            var countryIndex = nextRandomInt(0, model.country_list.length - 1);
            country = model.country_list[countryIndex];
            o.country = country;
            file_name += '/' + country.file_name;
        }
        if (type == 1 || type == 2) {
            var cityIndex = nextRandomInt(0, country.city_list.length - 1);
            city = country.city_list[cityIndex];
            o.city = city;
            file_name += '/' + city.file_name;
        }
        if (type == 2) {
            var departmentIndex = nextRandomInt(0, city.department_list.length - 1);
            department = city.department_list[departmentIndex];
            o.department = department;
            file_name += '/' + department.file_name;
        }
        arrayFileName.push(file_name);
        array.push(o);
    }
    link_map[map_key] = array;
    fs.writeSync(fd, map_key + ' <-> ' + arrayFileName.join(', ') + '\n');
}

function nextRandomInt(minRandom, maxRandom) {
    minRandom=Number(minRandom);
    maxRandom=Number(maxRandom);
    if (minRandom > maxRandom) {
        minRandom = maxRandom;
    }
    if (maxRandom > 0) {
        var range = 0;
        if (minRandom < maxRandom) {
            range = maxRandom - minRandom + 1;
            range = range = Math.floor(Math.random() * range);
        }
        minRandom += range;
    }
    if (minRandom < 0) {
        minRandom = 0;
    }
    return minRandom;
}

function readProperties(model, site) {
    readLines('sites/' + site + '/site.properties', function (line) {
        var index = line.indexOf('=');
        var key = line.substring(0, index).trim();
        var value = line.substring(index + 1).trim();
        model[key] = value;
    });
}


exports.initAll = function () {
    console.log('Start initData');
    var time = Date.now();
    var model = new models.Model();
//    properties
    readProperties(model, GLOBAL.site);
    console.log('read properties');

//    read file
    if (model.init_test == 'true') {
        exports.initTestData(model);
    }
    if (model.init_word2 == 'true') {
        exports.initWord2(model);
    }
    if (model.init_moneygram == 'true') {
        exports.initMoneygram(model);
    }
    time = Date.now() - time;
    console.log('read file ' + time + 'ms');
    time = Date.now();
    model.sort();
    time = Date.now() - time;
    console.log('sord ' + time + 'ms');
    time = Date.now();
    exports.initRandomText(model);
    time = Date.now() - time;
    console.log('initRandomText ' + time + 'ms');
    time = Date.now();
    exports.initRandomLink(model);
    time = Date.now() - time;
    console.log('initRandomLink ' + time + 'ms');
    console.log('Finish initData');
    return model;
}
